<template>
	<view class="page-box pad-30">
		<!-- 更换地址 -->
		<view class="bg-white pad-30 radius30" :class="addressId ? '': 'border'" @click="hanldeEditAddress">
			<view class="betweenX">
				<view class="font-30 color-text">选择地址</view>
				<view class="centerXY select shrink">
					<view class="font-26">选择</view>
					<up-icon color="#ABA9B4" name="arrow-right" size="13"></up-icon>
				</view>
			</view>
			<view class="betweenX centerXY mar-top-30" v-if="addressId">
				<view class="color-text">
					<view class="font-32">
						{{addressInfo?.province}}{{addressInfo?.city}}{{addressInfo?.region}}{{addressInfo?.street}}{{addressInfo?.detail}}
					</view>
					<view class="font-26 mar-top-20">联系电话: {{addressInfo?.tel}}</view>
				</view>
			</view>
			<view v-else class="color-error mar-top-30 font-30">您还没添加服务地址</view>
		</view>

		<!-- 更换时间 -->
		<!-- @click="hanldeDatetime" -->
		<view class="mar-top-30 pad-30 bg-white radius30" @click="hanldeDatetimePicker"
			:class="plan_begin_at == '' ? 'border' : ''">
			<view class="betweenX centerXY">
				<view class="font-30 color-text centerY timeBox">
					<view class="mar-right-10">上门时间</view>

					<uni-datetime-picker ref="datetimePickerRef" @hourChange="hourChange" v-if="calenderNum.length > 0"
						:calenderNum="calenderNum" :start="minDate" :end="maxDate" :isIcon="false" :border="false"
						hideSecond v-model="plan_begin_at" @change="hanldeConfirmDate"></uni-datetime-picker>

					<!-- <text v-if="plan_begin_at > 0"
						class="select mar-left-10">{{timeFormat(plan_begin_at, 'yyyy-mm-dd hh:00')}}</text>
					<text v-else class="mar-left-10 select">请选择上门时间</text> -->
				</view>
				<!-- <view class="centerXY select">
					<view class="font-26">修改</view>
					<up-icon color="#ABA9B4" name="arrow-right" size="13"></up-icon>
				</view> -->

			</view>
			<view v-if="plan_begin_at == ''" class="color-error mar-top-30 font-30">您还没添加服务时间</view>
		</view>

		<!-- 选择工人 -->
		<view class="mar-top-30 pad-30 bg-white radius30" :class="userList?.length > 0 ? '': 'border'"
			v-if="isWorkerBorder">

			<template v-if="userList?.length > 0">
				<view @click="hanldeAddWorker" class="centerY betweenX " v-for="worker in userList" :key="worker.id"
					:class="userList?.length > 1? 'mar-bottom-20': ''">
					<view class="centerY">
						<image class="avatar" :src="worker.avatar"></image>
						<view class="mar-left-20">
							<view class="font-26 color-text">{{worker.name}}</view>
						</view>
					</view>
					<view class="centerXY select">
						<view class="font-26">修改</view>
						<up-icon color="#ABA9B4" name="arrow-right" size="13"></up-icon>
					</view>
				</view>
			</template>
			<template v-else>

				<view @click="hanldeAddWorker" class="centerY betweenX">
					<view class="centerY">
						<image class="avatar" src="@/static/image/logo.png"></image>
						<view class="mar-left-20">
							<view class="font-26 color-text">请选择服务工人</view>
						</view>
					</view>
					<view class="centerXY select">
						<view class="font-26">选择</view>
						<up-icon color="#ABA9B4" name="arrow-right" size="13"></up-icon>
					</view>
				</view>
			</template>
			<view v-if="userList.length !== workerNum && workerNum >1" class="color-error mar-top-30 font-28">
				根据你的服务，请选择：{{workerNum}}工人</view>
			<view v-if="userList.length == 0" class="color-error mar-top-30 font-28">您还没添加服务工人</view>
		</view>

		<!-- 服务数据 -->
		<view class="workerInfo bg-white pad-40 radius30 mar-top-30">
			<view v-for="(item,index) in workList" :key="item.id" class="bg-white radius30 ">
				<view class="pad-bottom-30 list-border">
					<view class="font-32 color-text">{{item?.name}}</view>

					<!-- 服务：单位、数量 -->
					<view class="betweenX centerXY mar-top-30">
						<view class="font-30 color-text">{{item.unit}}</view>
						<view class="color-646464 font-26">
							<!--  -->
							<up-number-box :disablePlus="item.buy_num == item.max_buy_num"
								:disableMinus="item.buy_num == item.min_buy_num" v-model="item.buy_num"
								@change="handleChangeNum($event,item)" @blur="handleBlurNum($event,item)"
								:max="item.max_buy_num" :step="item.buy_step"></up-number-box>
						</view>
					</view>

					<!-- 服务总价 -->
					<view class="betweenX centerXY mar-top-30">
						<view class="font-30 color-text">服务总费用</view>
						<view class="color-646464 font-30">
							￥{{item?.amount}}元
						</view>
					</view>

					<!-- 消费明细 -->
					<view class="betweenX centerXY mar-top-30" v-for="(p,i) in item.amount_detail" :key="i">
						<view class="font-30 color-text">{{p.title}}</view>
						<view v-if="p.amount" class="color-error font-30">￥{{p.amount}}元</view>
					</view>

					<!-- 选择优惠券 -->
					<view v-if="userList?.length > 0" class="betweenX centerXY mar-top-30"
						@click="hanldeCoupon(item,index)">
						<view class="font-30 color-text flex align-center">
							<view class="mar-right-30">优惠券</view>
							<view class="couponType" v-if="item.user_coupon_id">{{item.couponInfo.name}}</view>
						</view>
						<view class="centerXY select">
							<view class="font-26 color-error">选择</view>
							<up-icon color="#ABA9B4" name="arrow-right" size="13"></up-icon>
						</view>
					</view>

					<!-- 渲染反馈问题 -->
					<view class="betweenX centerXY mar-top-30" v-for="qu in  item?.questions" :key="qu.id">
						<template v-if="qu.answer != null">
							<view class="flex-w" v-if="qu.type == 'checkbox'">
								<up-checkbox-group v-model="qu.answer" placement="row" iconPlacement="right">
									<up-checkbox labelColor="#1D1D1D" :customStyle="{marginBottom: '8px'}"
										:label="qu.title" :name="qu.id" :checked="qu.checked" />
								</up-checkbox-group>
							</view>
							<template v-if="qu.type == 'radio'">
								<view class="font-30 flex-w">{{qu.title}}</view>
								<up-radio-group v-model="qu.answerVal" placement="row">
									<up-radio :customStyle="{marginLeft: '8px'}" v-for="(an,index) in qu.answer"
										:key="index" :label="an" :name="an">
									</up-radio>
								</up-radio-group>
							</template>
						</template>
					</view>

					<!-- 备注 -->
					<view class="mar-top-30">
						<view class="font-30 color-text mar-bottom-10">备注：</view>
						<up-textarea count maxlength="100" v-model="item.user_remark" placeholder="请输入备注"></up-textarea>
					</view>
				</view>
			</view>
		</view>

		<!-- 按钮 -->
		<view class="betweenX button-bottom centerY">
			<view class="flex-w">
				<view class="font-36 color-error" v-if="total"><text class="font-24">￥</text>{{total}}元</view>
				<view class="font-24 yuanjia color-CCCCCC">原价￥{{total_amount}}元</view>
			</view>
			<view @click="debounce(hanldeConfirmOrder,500)" class="btn3 button-style">去支付</view>
		</view>

		<!-- 选择时间 -->
		<!-- 	<up-datetime-picker :minDate="minDate" :maxDate="maxDate" ref="datetimePickerRef" :formatter="formatter"
			@confirm="hanldeConfirmDate" @cancel="isTime = false" :show="isTime" step="01:00:00" v-model="pickerTime"
			format="YYYY-MM-DD HH:mm" :mode="workTimeMode">
		</up-datetime-picker> -->

		<!-- 地址弹窗工人弹窗  -->
		<up-popup :show="isAddress" round="20" bgColor="#f4f5f9" closeable @close="isAddress =false">
			<view class="pad-30 font-36 color-text">选择地址</view>
			<addressList rightButtonText="确定" @hanldeNext="hanldeNext"></addressList>
		</up-popup>

		<!-- 选择优惠券 -->
		<up-popup :show="isCoupon" round="20" bgColor="#f4f5f9" closeable @close="isCoupon = false">
			<view class="pad-30 font-36 color-text text-center">选择优惠券</view>
			<couponList @hanldeCancel="isCoupon = false" :userCouponId="couponId" @hanldeConfirm="handleCoupon">
			</couponList>
		</up-popup>

		<!-- 选择支付方式 -->
		<up-popup v-if="isPay" :show="isPay" round="20" bgColor="#f4f5f9" closeable @close="hanldeIsPay">
			<view class="pad-30 font-36 color-text">选择支付方式</view>
			<pay-list :orderNos="orderNos"></pay-list>
		</up-popup>

		<suspend icon="/static/image/service.jpg"></suspend>
	</view>
</template>

<script setup>
	// 引入decimal.js 保证显示不失真
	import Decimal from 'decimal.js';
	import util from '@/util/util.js';
	import { useStore } from '@/store/useCounterStore';
	import { nextTick } from 'vue';
	import { ref, watch, computed, watchEffect } from 'vue';
	import { addressDetail, orderMultiCreate, orderPreview, workMulti, enableWorkerCnt } from '@/api/index.js'
	import { dataReportFun } from '@/util/dataReport.js'
	import { onShow, onLoad, onUnload } from '@dcloudio/uni-app'
	import { timeFormat, debounce } from '@/node_modules/uview-plus';

	const store = useStore();
	const datetimePickerRef = ref(null);
	// 接收页面传参
	const props = ref({});
	onLoad((option) => {
		props.value = option;
		getWorkMulti();
		dataReportFun({
			event: "client.page_view",
		})
	});

	const hanldeDatetimePicker = () => {
		datetimePickerRef.value.show();
	}

	const hourChange = (data) => {
		getAddressDetail().then(res => {
			let timeData = {
				works: workList.value.map(i => {
					return {
						work_id: i.work_id,
						buy_num: i.buy_num,
					}
				}),
				lat: res.lat,
				lgt: res.lgt,
				timestamp_list: util.getDatesToEndOfMonth(data?.month, data?.hour)
			}

			enableWorkerCnt(timeData).then(time => {
				calenderNum.value = time.data.lists;
			})
		})
	}

	// 页面卸载
	onUnload(() => {
		store.reset();
	})

	// 获取工人列表
	const userList = computed(() => {
		return store.workerItme
	})

	// 服务id
	const computedWorkIds = computed(() => {
		return store.workIds
	})

	// 监听服务id改动和变化 & 监听工人数据
	watchEffect(async () => {
		if (userList.value.length > 0) {
			await nextTick();
			setTimeout(() => {
				setOrderPreview();
			}, 400)
		}
	})

	// 监听自动打开工人弹窗、工人未选样式
	const isWorkerBorder = ref(false);
	// 提交得数据
	const formData = ref({
		plan_begin_at: store.workerParams.plan_begin_at
	})

	// 计算plan_begin_at
	const plan_begin_at = computed(() => {
		return store.workerParams.plan_begin_at
	})

	// 获取地址id
	let addressId = ref(uni.getStorageSync('addressId'));
	// 切换地址
	const hanldeNext = (data) => {
		uni.setStorageSync('addressId', data.id);
		addressId.value = data.id;
		isAddress.value = false;
		getAddressDetail();
		hourChange();
	}

	// 通过本地缓存获取地址
	const addressInfo = ref({});
	const getAddressDetail = () => {
		return new Promise((resolve, reject) => {
			if (addressId.value) {
				addressDetail({
					id: addressId.value
				}).then(res => {
					if (res?.code == '10014') {
						uni.removeStorageSync('addressId');
						addressId.value = "";
						return
					}
					if (res?.code == 200) {
						let info = res.data.info;
						addressInfo.value = info;
						store.workerParams.lat = info?.lat;
						store.workerParams.lgt = info?.lgt;
						resolve(info);
					} else {
						reject("info", '错误');
					}
				})
			}
		})
	}

	// 监听地址和时间改动变化
	watch([addressId, plan_begin_at, computedWorkIds], async ([newAdd, newPlan, newComputedWorkIds]) => {
		if (newAdd && newPlan != '') {
			isWorkerBorder.value = true;
			if (newComputedWorkIds.length > 0) {
				await nextTick();
				getWorkMulti();
			}
		} else {
			isWorkerBorder.value = false;
		}

	}, {
		deep: true,
		immediate: true
	});

	// 根据工种id获取详情
	const workList = ref([]);
	const workTimeMode = ref();
	const getWorkMulti = () => {
		workMulti({
			work_ids: store.workIds
		}).then(res => {
			if (res.code == 200) {
				let lists = res.data?.lists || [];
				// 重置数据
				emptyData(lists);
				// 选择时间格式
				if (lists?.length > 1) {
					if (lists[0]?.work_time_mode == 1) {
						workTimeMode.value = 'datetime';
					} else if (worker.work_time_mode == 2) {
						workTimeMode.value = 'date';
					};
				}
				workList.value = lists;
				hourChange()
			} else if (res.code == 10004) {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		})
	}


	// 打开选择时间
	const isTime = ref(false);
	// 设置时间选择的区间
	const minDate = Date.now() + (2 * 60 * 60 * 1000); // 开始时间默认2小时过后
	const currentDate = new Date(Date.now());
	// 最大可以预约2个月之后的
	const maxDate = currentDate.setMonth(currentDate.getMonth() + 2);
	// 选择时间
	const dateMode = ref("date");
	const buy_num = ref(1);
	const pickerTime = ref(Date.now() + (2 * 60 * 60 * 1000))
	// 改变时间状态
	const hanldeDatetime = () => {
		isTime.value = true;
		store.workerItme = [];
	}

	// 跳转选择工人页面
	const workerNum = ref(1);
	// 点击切换工人
	const hanldeAddWorker = () => {
		// 只有一个服务才能选多个工人
		store.workerParams.works = workList.value.map(i => {
			return {
				work_id: i.work_id,
				buy_num: i.buy_num,
			}
		})

		uni.navigateTo({
			url: '/pages/order/orderWork/orderWork?num=' + workerNum.value
		})
	}

	// 修改地址
	const isAddress = ref(false);
	const hanldeEditAddress = () => {
		isAddress.value = true;
		store.workerItme = [];
	}

	// 关闭时间选择
	const hanldeConfirmDate = (e) => {
		formData.value.plan_begin_at = e;
		store.workerParams.plan_begin_at = e;
		store.workerItme = [];
	}

	// 失去焦点判断 不能选着小于最小购买量
	const handleBlurNum = (e, item) => {
		if (e.value < item.min_buy_num) {
			uni.showToast({
				title: item.name + '选择数量不能小于' + item.min_buy_num,
				duration: 1500,
				icon: 'none'
			})
			item.buy_num = item.min_buy_num;
		}
	}

	// 调用价格计算
	const handleChangeNum = (e, item) => {
		item.buy_num = e.value;
		if (workList.value.length === 1) {
			// 需要选择工人的数量
			workerNum.value = Math.ceil(e.value / workList.value[0].max_once_each_person);
			// 验证下单正确
			store.workerItme = [];

			// 清空数据
			emptyData(workList.value);
		} else {
			setOrderPreview();
		}
	}

	// 选择优惠券 
	const handleCoupon = (data) => {
		if (data?.id != undefined) {
			workList.value[shopIndex.value].user_coupon_id = data.id;
			workList.value[shopIndex.value].couponInfo = data;
		} else {
			workList.value[shopIndex.value].user_coupon_id = "";
			workList.value[shopIndex.value].couponInfo = {};
		}
		setOrderPreview();
		isCoupon.value = false;
	}

	const formatter = (type, value) => {
		if (type === 'minute') {
			return `00`;
		}
		return value;
	};

	// 选择优惠券
	let isCoupon = ref(false);
	// 当前服务id 
	let shopIndex = ref(0);
	// 优惠券id 
	let couponId = ref(0);
	// 优惠后价格
	let total_amount = ref('--');
	// 优惠前价格
	const total = ref('--');
	const hanldeCoupon = (item, index) => {
		shopIndex.value = index;
		couponId.value = item.user_coupon_id;
		isCoupon.value = true;
	}

	// 订单校验接口
	const setOrderPreview = () => {
		uni.showLoading({
			title: '加载中...',
		})
		orderPreview({
			// 地址id
			user_address_id: uni.getStorageSync('addressId'),
			// 上门时间
			plan_begin_at: store.workerParams.plan_begin_at,
			// 工人id
			worker_ids: store.workerItme.map(i => i.id) || [],
			// 服务
			works: getWorkerData(workList.value)
		}).then(res => {
			let previewList = res.data.service_order_task;
			// 成功遍历价格
			if (res.code == 200) {
				workList.value.forEach((x, y) => {
					previewList.forEach((o, i) => {
						if (o.work_id === x.work_id) {
							x.act_pay_amount = o.act_pay_amount;
							x.amount = o.amount;
							x.amount_detail = o.amount_detail;
						}
					})
				})
				// 生成总结
				total.value = res.data.total_act_pay_amount;
				total_amount.value = res.data.total_amount;
				uni.hideLoading();
			} else {
				emptyData(workList.value);
				uni.hideLoading();
			}
		})
	}

	// 清空数据函数
	const emptyData = (data) => {
		data.forEach(item => {
			// 服务备注
			item.user_remark = "";
			// 购买数量
			item.buy_num = item.min_buy_num;
			// 服务价格
			item.amount = "--";
			// 实付价格
			item.act_pay_amount = "--";
			// 优惠券id
			item.user_coupon_id = "";
			// 优惠券回显数据
			item.couponInfo = [];
			// 价格后
			total_amount.value = "--"
			// 优惠前
			total.value = "--"

			if (data?.length > 1) {
				item.max_buy_num = item.max_once_each_person;
			} else {
				item.max_buy_num = 9999;
			}
		})

		// 生成总结
		total.value = "--";
		total_amount.value = "--";
	}

	// 遍历服务
	const getWorkerData = (data) => {
		return data.map(i => {
			i.questions.forEach(i => {
				if (i.answer[0] == i.id) {
					i.answer = ['有']
				} else {
					i.answer = ['无']
				}
			})
			return {
				work_id: i.work_id,
				questions: i.questions,
				buy_num: i.buy_num,
				user_remark: i.user_remark,
				user_coupon_id: i.user_coupon_id
			}
		})
	}

	// 提交数据创建订单
	const isPay = ref(false);
	const orderNos = ref([]);
	const hanldeConfirmOrder = () => {
		//#ifdef H5
		var wx = window.navigator.userAgent.toLowerCase();
		if (wx.match(/MicroMessenger/i) == 'micromessenger') { // 是微信端
			uni.reLaunch({
				url: "/pages/wxBrowseTips/wxBrowseTips"
			})
			return;
		}
		// #endif

		let data = {
			// 地址id
			user_address_id: uni.getStorageSync('addressId'),
			// 上门时间
			plan_begin_at: store.workerParams.plan_begin_at,
			// 工人id
			worker_ids: store.workerItme.map(i => i.id) || [],
			// 服务
			works: getWorkerData(workList.value)
		}

		// 选择支付方式
		orderMultiCreate(data).then(res => {
			if (res.code == 200) {
				isPay.value = true;
				orderNos.value = res.data.order_nos;
			} else if (res.code == 20042) {
				isPay.value = false;
				uni.$u.toast(res.msg);
				uni.navigateBack();
			} else {
				dataReportFun({
					event: "client.report_error",
					ext: data,
					content: res.msg
				})
			}
		}).catch(err => {
			isPay.value = false;
			uni.navigateBack();
		})
	}

	// 点击关闭选择支付弹窗跳转去订单页面
	const hanldeIsPay = () => {
		isPay.value = false;
		uni.switchTab({
			url: '/pages/order/order/order'
		})
	}

	const calenderNum = ref([]);
	// 获取工人信息
	onShow(() => {
		getAddressDetail();
	})
</script>

<style scoped lang="scss">
	.yuanjia {
		text-decoration: line-through;
	}

	.border {
		border: 1rpx solid #FF4913;
	}

	.page-box {
		padding-bottom: 200rpx;
	}

	// .workerInfo {
	// 	position: relative;
	// }

	:deep(.u-radio-group) {
		flex: none;
	}

	.button {
		background: red;
		text-align: center;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}

	.select {
		color: #ABA9B4;
	}

	:deep(.u-checkbox) {
		width: 100%;
	}


	.button-bottom {
		width: 100%;
		padding: 35rpx 40rpx;
		box-sizing: border-box;
		background: white;
		position: fixed;
		bottom: 0rpx;
		left: 0rpx;
		z-index: 2;
	}

	.btn {
		height: 100rpx;
		border-radius: 50rpx 0 0 50rpx;
		padding: 0 40rpx;
		line-height: 100rpx;
		background: rgba(0, 85, 254, 0.1);
		text-align: center;
		color: $uni-color-primary;
	}

	.btn2 {
		height: 100rpx;
		border-radius: 0 50rpx 50rpx 0;
		padding: 0 40rpx;
		line-height: 100rpx;
		text-align: center;
	}

	.btn3 {
		width: 220rpx;
		height: 100rpx;
		border-radius: 50rpx;
		padding: 0 40rpx;
		line-height: 100rpx;
		text-align: center;
	}

	.couponType {
		background: linear-gradient(270deg, #FF4913 0%, #FE9013 100%);
		padding: 8rpx 15rpx;
		border-radius: 30rpx;
		font-size: 28rpx;
		color: white;
	}

	.list-border {
		border-bottom: 2rpx solid #F4F6F8;
	}

	.timeBox {
		width: 100%;
	}
</style>